// pages/login/login.js
const FN = require('../../utils/public');
import loginAPI from '../../api/loginAPI'
import { configApp } from '../../utils/config'
var app = getApp();
const qiniuUploader = require("../../utils/qiniuUploader");
const defaultAvatarUrl = 'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    defaultAvatarUrl: defaultAvatarUrl,
    wxUserInfo: {},
    nickName: '',
    showWxuserinfoUseto: false,
    hasUserBtn: true
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.setData({
      wxUserInfo: app.globalData.wxUserInfo
    })
  },

  // 授权获取用户信息
  bindGetUserInfo: function (e) {
    this.saveWXinfo();
  },

  // 保存用户信息
  saveWXinfo: function () {
    var that = this;
    wx.login({
      success(result) {
        if (result.code) {
          const userInfo = {
            avatarUrl: that.data.wxUserInfo.avatarUrl,
            nickName: that.data.wxUserInfo.nickName,
            code: result.code
          }
          loginAPI.codetransformationOpenId(userInfo).then(res => {
            FN.Toast(res.message);
            app.globalData.wxUserInfo.avatarUrl = that.data.wxUserInfo.avatarUrl
            app.globalData.wxUserInfo.nickName = that.data.wxUserInfo.nickName// 更新全局的微信信息
            if (res.code == '200') {
              FN.Toast('登录成功')
            }
            var o = {
              data: that.data.wxUserInfo,
              timeStr: Date.now()
            };
            wx.setStorage({
              key: "wxInfoDiff",
              data: o
            })
            wx.setStorage({
              key: "wxUserInfo",
              data: that.data.wxUserInfo
            })
            setTimeout(function () {
              wx.navigateBack({
                delta: 0,
              })
            }, 1000)
          })
        } else {
          FN.Toast('登录失败')
        }
      }
    })

  },

  onChooseAvatar(e) {
    const { avatarUrl } = e.detail
    this.uploadUserHeaderImg(avatarUrl)
  },

  uploadUserHeaderImg(avatarUrl) {
    var that = this, filePath = avatarUrl, fileName = "avatarUrl" + new Date().getTime() + ".png";
    this.initQiniu();
    // 向七牛云上传
    qiniuUploader.upload(filePath, (res) => {
      res.fileName = fileName;
      if (res.hasOwnProperty("error")) {
        wx.showToast({
          title: '上传失败，请重新上传',
          icon: 'none',
          duration: 2000
        })
        that.initQiniu();
      } else {
        const avatarUrl = 'wxUserInfo.avatarUrl'
        this.setData({
          [avatarUrl]: res.fileURL
        })
      }
    }, (error) => {
      console.error('error: ' + JSON.stringify(error));
    }, { key: fileName }, (progress) => {
    }, cancelTask => that.setData({ cancelTask })
    );
  },

  initQiniu: function () {
    var options = {
      region: 'ECN',
      uptokenURL: configApp.api_base_url + 'qiniu/getUploadToken',
      domain: configApp.qiniuBucketURLPrefix,
      shouldUseQiniuFileName: true
    }
    // 将七牛云相关配置初始化进本sdk
    qiniuUploader.init(options);
  },
  // 微信用途
  showWxuserinfoUsetoTip() {
    this.setData({
      showWxuserinfoUseto: !this.data.showWxuserinfoUseto
    })
  },
  // 监听昵称改变
  onChangeNickname(e) {
    let nickName = "wxUserInfo.nickName"
    this.setData({
      [nickName]: e.detail.value
    })
  },
})